<!-- stories/templates/stories/story_library.html -->
{% extends 'stories/base.html' %}
{% load static %}

{% block title %}故事库 - AI故事生成网站{% endblock %}

{% block content %}
<div class="container">
    <div class="page-header">
        <h1>故事库</h1>
        <p>探索所有精彩故事</p>
    </div>

    <div class="library-filters">
        <div class="filter-row">
            <div class="filter-category">
                <label>分类筛选:</label>
                <select id="categoryFilter">
                    <option value="">全部分类</option>
                    {% for category in categories %}
                        <option value="{{ category.id }}" {% if current_category and category.id == current_category.id %}selected{% endif %}>
                            {{ category.name }}
                        </option>
                    {% endfor %}
                </select>
            </div>

            <div class="filter-sort">
                <label>排序方式:</label>
                <select id="sortFilter">
                    <option value="newest" {% if sort_by == 'newest' %}selected{% endif %}>最新发布</option>
                    <option value="rating" {% if sort_by == 'rating' %}selected{% endif %}>最高评分</option>
                    <option value="views" {% if sort_by == 'views' %}selected{% endif %}>最多浏览</option>
                </select>
            </div>
        </div>

        <div class="search-box">
            <input type="text" id="searchInput" placeholder="搜索故事标题或内容..." value="{{ search_query|default:'' }}">
            <button id="searchButton">搜索</button>
        </div>
    </div>

    <!-- 搜索结果区域 -->
    <div id="searchResultsContainer" style="display: none;">
        <h2>搜索结果</h2>
        <div class="story-grid library-grid" id="searchResultsGrid">
            <!-- 搜索结果将通过JavaScript动态插入这里 -->
        </div>
        <!-- 搜索结果分页 -->
        <div class="pagination-container" id="searchPaginationContainer">
            <!-- 分页将通过JavaScript动态插入这里 -->
        </div>
    </div>

    <!-- 默认故事列表 -->
    <div id="defaultStoryList" {% if search_query %}style="display: none;"{% endif %}>
        {% if stories %}
            <div class="story-grid library-grid">
                {% for story in stories %}
                    <div class="story-card">
                        <div class="card-cover">
                            <a href="{% url 'stories:story_detail' story.id %}">
                                {% if story.cover_image %}
                                    <img src="{{ story.cover_image.url }}" alt="{{ story.title }}">
                                {% else %}
                                    <div class="cover-text">{{ story.title|slice:":8" }}</div>
                                {% endif %}
                            </a>
                        </div>
                        <div class="card-content">
                            <h3><a href="{% url 'stories:story_detail' story.id %}">{{ story.title }}</a></h3>
                            <div class="card-meta">
                                <span class="author">作者: {{ story.author.username }}</span>
                                <span class="category">分类: {{ story.category.name }}</span>
                                <span class="rating">
                                    <span class="star-rating">
                                        {% for i in "12345" %}
                                            {% if forloop.counter <= story.average_rating|floatformat:"0"|add:"0" %}
                                                ★
                                            {% else %}
                                                ☆
                                            {% endif %}
                                        {% endfor %}
                                    </span>
                                    ({{ story.rating_count }})
                                </span>
                            </div>
                            <p class="card-excerpt">{{ story.content|truncatewords:15 }}</p>
                            <div class="card-footer">
                                <span class="views">👁️ {{ story.view_count }}</span>
                                <span class="date">{{ story.created_at|date:"Y-m-d" }}</span>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            </div>
            
            <!-- 分页 -->
            {% if stories.has_other_pages %}
            <div class="pagination-container">
                <div class="pagination">
                    <a href="?page=1{% if current_category %}&category={{ current_category.id }}{% endif %}{% if sort_by %}&sort={{ sort_by }}{% endif %}{% if search_query %}&q={{ search_query }}{% endif %}" {% if stories.number == 1 %}class="disabled"{% endif %}>&laquo; 首页</a>
                    {% if stories.has_previous %}
                        <a href="?page={{ stories.previous_page_number }}{% if current_category %}&category={{ current_category.id }}{% endif %}{% if sort_by %}&sort={{ sort_by }}{% endif %}{% if search_query %}&q={{ search_query }}{% endif %}">&lsaquo; 上一页</a>
                    {% else %}
                        <a class="disabled">&lsaquo; 上一页</a>
                    {% endif %}

                    {% for num in stories.paginator.page_range %}
                        {% if stories.number == num %}
                            <span class="current">{{ num }}</span>
                        {% elif num > stories.number|add:'-3' and num < stories.number|add:'3' %}
                            <a href="?page={{ num }}{% if current_category %}&category={{ current_category.id }}{% endif %}{% if sort_by %}&sort={{ sort_by }}{% endif %}{% if search_query %}&q={{ search_query }}{% endif %}">{{ num }}</a>
                        {% endif %}
                    {% endfor %}

                    {% if stories.has_next %}
                        <a href="?page={{ stories.next_page_number }}{% if current_category %}&category={{ current_category.id }}{% endif %}{% if sort_by %}&sort={{ sort_by }}{% endif %}{% if search_query %}&q={{ search_query }}{% endif %}">下一页 &rsaquo;</a>
                    {% else %}
                        <a class="disabled">下一页 &rsaquo;</a>
                    {% endif %}
                    <a href="?page={{ stories.paginator.num_pages }}{% if current_category %}&category={{ current_category.id }}{% endif %}{% if sort_by %}&sort={{ sort_by }}{% endif %}{% if search_query %}&q={{ search_query }}{% endif %}" {% if stories.number == stories.paginator.num_pages %}class="disabled"{% endif %}>末页 &raquo;</a>
                </div>
            </div>
            {% endif %}
        {% else %}
            <div class="no-stories">
                <p>暂无符合条件的故事</p>
            </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 分类筛选
    $('#categoryFilter').change(function() {
        var categoryId = $(this).val();
        var sort = $('#sortFilter').val();
        var searchQuery = $('#searchInput').val().trim();
        var url = '/library/?';

        if (categoryId) {
            url += 'category=' + categoryId + '&';
        }
        url += 'sort=' + sort;
        
        if (searchQuery) {
            url += '&q=' + encodeURIComponent(searchQuery);
        }

        window.location.href = url;
    });

    // 排序筛选
    $('#sortFilter').change(function() {
        var categoryId = $('#categoryFilter').val();
        var sort = $(this).val();
        var searchQuery = $('#searchInput').val().trim();
        var url = '/library/?';

        if (categoryId) {
            url += 'category=' + categoryId + '&';
        }
        url += 'sort=' + sort;
        
        if (searchQuery) {
            url += '&q=' + encodeURIComponent(searchQuery);
        }

        window.location.href = url;
    });

    // 搜索功能
    $('#searchButton').click(function() {
        performSearch(1); // 默认从第1页开始
    });

    $('#searchInput').keypress(function(e) {
        if (e.which == 13) {  // Enter键
            performSearch(1); // 默认从第1页开始
        }
    });

    function performSearch(page) {
        var query = $('#searchInput').val().trim();
        if (!query) {
            // 如果搜索词为空，显示默认故事列表
            $('#searchResultsContainer').hide();
            $('#defaultStoryList').show();
            return;
        }

        // 显示加载状态
        $('#searchResultsGrid').html('<div class="loading">搜索中...</div>');

        $.get('/ajax/search/', {q: query, page: page}, function(data) {
            if (data.results.length > 0) {
                var html = '';
                $.each(data.results, function(index, story) {
                    // 构建星级评分
                    var starRating = '';
                    var fullStars = Math.round(story.average_rating);
                    for (var i = 1; i <= 5; i++) {
                        if (i <= fullStars) {
                            starRating += '★';
                        } else {
                            starRating += '☆';
                        }
                    }
                    
                    // 构建故事卡片HTML，样式与首页保持一致
                    html += '<div class="story-card">' +
                               '<div class="card-cover">' +
                                   '<a href="/story/' + story.id + '/">' +
                                       '<div class="cover-text">' + story.title.substring(0, 8) + '</div>' +
                                   '</a>' +
                               '</div>' +
                               '<div class="card-content">' +
                                   '<h3><a href="/story/' + story.id + '/">' + story.title + '</a></h3>' +
                                   '<div class="card-meta">' +
                                       '<span class="author">作者: ' + story.author + '</span>' +
                                       '<span class="category">分类: ' + story.category + '</span>' +
                                       '<span class="rating">' +
                                           '<span class="star-rating">' + starRating + '</span>' +
                                           ' (' + story.rating_count + ')' +
                                       '</span>' +
                                   '</div>' +
                                   '<p class="card-excerpt">' + story.content.substring(0, 60) + '...</p>' +
                                   '<div class="card-footer">' +
                                       '<span class="views">👁️ ' + story.view_count + '</span>' +
                                       '<span class="date">' + story.created_at + '</span>' +
                                   '</div>' +
                               '</div>' +
                           '</div>';
                });
                
                $('#searchResultsGrid').html(html);
                
                // 生成分页
                generatePagination(data.total_pages, data.current_page, query);
                
                $('#searchResultsContainer').show();
                $('#defaultStoryList').hide();
            } else {
                $('#searchResultsGrid').html('<div class="no-stories"><p>未找到相关故事</p></div>');
                $('#searchPaginationContainer').html('');
                $('#searchResultsContainer').show();
                $('#defaultStoryList').hide();
            }
        }).fail(function() {
            $('#searchResultsGrid').html('<div class="no-stories"><p>搜索失败，请稍后重试</p></div>');
            $('#searchPaginationContainer').html('');
            $('#searchResultsContainer').show();
            $('#defaultStoryList').hide();
        });
    }
    
    // 生成分页HTML
    function generatePagination(totalPages, currentPage, query) {
        if (totalPages <= 1) {
            $('#searchPaginationContainer').html('');
            return;
        }
        
        var paginationHtml = '<div class="pagination">';
        
        // 首页
        paginationHtml += '<a href="#" onclick="performSearch(1); return false;" ' + (currentPage == 1 ? 'class="disabled"' : '') + '>&laquo; 首页</a>';
        
        // 上一页
        if (currentPage > 1) {
            paginationHtml += '<a href="#" onclick="performSearch(' + (currentPage - 1) + '); return false;">&lsaquo; 上一页</a>';
        } else {
            paginationHtml += '<a class="disabled">&lsaquo; 上一页</a>';
        }
        
        // 页码
        for (var i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += '<span class="current">' + i + '</span>';
            } else if (i >= currentPage - 2 && i <= currentPage + 2) {
                paginationHtml += '<a href="#" onclick="performSearch(' + i + '); return false;">' + i + '</a>';
            }
        }
        
        // 下一页
        if (currentPage < totalPages) {
            paginationHtml += '<a href="#" onclick="performSearch(' + (currentPage + 1) + '); return false;">下一页 &rsaquo;</a>';
        } else {
            paginationHtml += '<a class="disabled">下一页 &rsaquo;</a>';
        }
        
        // 末页
        paginationHtml += '<a href="#" onclick="performSearch(' + totalPages + '); return false;" ' + (currentPage == totalPages ? 'class="disabled"' : '') + '>末页 &raquo;</a>';
        
        paginationHtml += '</div>';
        $('#searchPaginationContainer').html(paginationHtml);
    }
});
</script>
{% endblock %}